package com.imay.live.helper;

import android.content.Context;
import android.graphics.Bitmap;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.FragmentManager;
import android.view.View;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.imay.base.helper.ActivityHelper;
import com.imay.base.helper.NetworkHelper;
import com.imay.live.manager.UploadFileManager;
import com.imay.live.model.MenuItemModel;
import com.imay.live.proto.ErrorResult;
import com.imay.live.proto.ProtoError;
import com.imay.live.proto.ReportCategory;
import com.imay.live.proto.Result;
import com.imay.live.proto.ResultCode;
import com.imay.live.proto.helper.ProtoCallBack;
import com.imay.live.proto.helper.ProtoHttpFactory;
import com.imay.live.proto.helper.ProtoRequestHelper;
import com.imay.live.utils.ToastUtil;
import com.imay.live.view.dialog.ChoiseDialogFragment;
import com.imay.live.R;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * 举报公共类
 * Created by chan on 2017/5/13.
 */

public class RepostHelper {

    private int imgStatus;

    private final int STATUS_SAVEING = 1;
    private final int STATUS_SAVE_SUCCESS = 2;
    private final int STATUS_SAVE_FAILER = 3;
    private final int STATUS_SAVE_ERROR = 4;

    private final int TAG = 3;

    /**
     * ==========
     */
    private final int STATUS_ROOM = 1;
    private final int STATUS_VIDEO = 2;
    private final int STATUS_IMAGE = 3;
    private final int STATUS_USER = 4;

    private final String savePath;
    private final String filePath;

    private List<MenuItemModel> string = new ArrayList<>();

    private final int MENU_ACTION_REPORT_01 = 301;
    private final int MENU_ACTION_REPORT_02 = 302;
    private final int MENU_ACTION_REPORT_03 = 303;
    private final int MENU_ACTION_REPORT_04 = 304;
    private final int MENU_ACTION_REPORT_05 = 305;

    private Context mContext;

    private static RepostHelper instance;

    public static RepostHelper getInstance() {
        if (instance == null) {
            instance = new RepostHelper();
        }
        return instance;
    }

    public RepostHelper() {
        savePath = getSDCardPath() + "/imay/images/";
        filePath = savePath + "/screen.jpg";

        string.add(new MenuItemModel(MENU_ACTION_REPORT_01, R.string.str_dynamics_report_01));
        string.add(new MenuItemModel(MENU_ACTION_REPORT_02, R.string.str_dynamics_report_02));
        string.add(new MenuItemModel(MENU_ACTION_REPORT_03, R.string.str_dynamics_report_03));
        string.add(new MenuItemModel(MENU_ACTION_REPORT_04, R.string.str_dynamics_report_04));
        string.add(new MenuItemModel(MENU_ACTION_REPORT_05, R.string.str_dynamics_report_05));
    }


    /**
     * 举报房间
     *
     * @param fragmentManager
     * @param roomId
     * @param uid
     * @param screenshot      截图信息
     */
    public void reportRoom(final FragmentManager fragmentManager, final Context context, long roomId, long uid, final String screenshot) {
        mContext = context;
        final RepostModel repostModel = new RepostModel();
        repostModel.reportStatus = STATUS_ROOM;
        repostModel.roomId = roomId;
        repostModel.uid = uid;

        ChoiseDialogFragment.show(fragmentManager, string, TAG, new ChoiseDialogFragment.OnItemClickListener() {
            @Override
            public void itemClick(int tagCallBack, int position, MenuItemModel item) {
                final int category = getCategory(item);
                repostModel.category = category;
                if (!NetworkHelper.getInstance().hasConnection()) {
                    ErrorResult.toastError(mContext, ResultCode.CodeNetErrorAction);
                    return;
                }
                ProtoRequestHelper.task(ProtoHttpFactory.requestReportRoom(repostModel.roomId, repostModel.uid, repostModel.category, screenshot)).setTag(this.hashCode()).request(protoCallBack);
            }
        });
    }

    /**
     * 举报视频
     *
     * @param fragmentManager
     * @param context
     * @param feedId
     * @param uid
     * @param filePath      举报的文件链接
     */
    public void reportVideo(final FragmentManager fragmentManager, final Context context, long feedId, long uid, final String filePath) {
        mContext = context;
        final RepostModel repostModel = new RepostModel();
        repostModel.reportStatus = STATUS_VIDEO;
        repostModel.feedId = feedId;
        repostModel.uid = uid;

        ChoiseDialogFragment.show(fragmentManager, string, TAG, new ChoiseDialogFragment.OnItemClickListener() {
            @Override
            public void itemClick(int tagCallBack, int position, MenuItemModel item) {
                final int category = getCategory(item);
                repostModel.category = category;
                if (!NetworkHelper.getInstance().hasConnection()) {
                    ErrorResult.toastError(mContext, ResultCode.CodeNetErrorAction);
                    return;
                }
                ProtoRequestHelper.task(ProtoHttpFactory.requestReportVideo(repostModel.feedId, repostModel.uid, repostModel.category, filePath)).setTag(this.hashCode()).request(protoCallBack);
            }
        });
    }


    /**
     * 举报图片
     *
     * @param fragmentManager
     * @param context
     * @param feedId
     * @param uid
     * @param filePath        动态对应图片
     */
    public void reportPicture(final FragmentManager fragmentManager, Context context, long feedId, long uid, final String filePath) {
        mContext = context;
        final RepostModel repostModel = new RepostModel();
        repostModel.reportStatus = STATUS_IMAGE;
        repostModel.feedId = feedId;
        repostModel.uid = uid;

        ChoiseDialogFragment.show(fragmentManager, string, TAG, new ChoiseDialogFragment.OnItemClickListener() {
            @Override
            public void itemClick(int tagCallBack, int position, MenuItemModel item) {
                final int category = getCategory(item);
                repostModel.category = category;
                if (!NetworkHelper.getInstance().hasConnection()) {
                    ErrorResult.toastError(mContext, ResultCode.CodeNetErrorAction);
                    return;
                }
                ProtoRequestHelper.task(ProtoHttpFactory.requestReportPicture(repostModel.feedId, repostModel.uid, repostModel.category, filePath)).setTag(this.hashCode()).request(protoCallBack);
            }
        });
    }

    /**
     * 举报个人
     *
     * @param fragmentManager
     * @param context
     * @param uid
     * @param screenshot      是否需要截图
     */
    public void reportUser(final FragmentManager fragmentManager, final Context context, long uid, final boolean screenshot) {
        mContext = context;
        final RepostModel repostModel = new RepostModel();
        repostModel.reportStatus = STATUS_USER;
        repostModel.uid = uid;

        ChoiseDialogFragment.show(fragmentManager, string, TAG, new ChoiseDialogFragment.OnItemClickListener() {
            @Override
            public void itemClick(int tagCallBack, int position, MenuItemModel item) {
                final int category = getCategory(item);
                repostModel.category = category;
                if (!NetworkHelper.getInstance().hasConnection()) {
                    ErrorResult.toastError(mContext, ResultCode.CodeNetErrorAction);
                    return;
                }
                if (screenshot) {
                    saveCurrentImage(repostModel);
                } else {
                    ProtoRequestHelper.task(ProtoHttpFactory.requestReportUser(repostModel.uid, repostModel.category, null)).setTag(this.hashCode()).request(protoCallBack);
                }
            }
        });
    }

    /**
     * ======获取举报类型=============
     *
     * @param item
     */
    private int getCategory(MenuItemModel item) {
        int category = ReportCategory.Unknow;
        switch (item.getAction()) {
            case MENU_ACTION_REPORT_01:
                category = ReportCategory.Obscene;
                break;
            case MENU_ACTION_REPORT_02:
                category = ReportCategory.Fraud;
                break;
            case MENU_ACTION_REPORT_03:
                category = ReportCategory.Violence;
                break;
            case MENU_ACTION_REPORT_04:
                category = ReportCategory.DrugOrGambling;
                break;
            case MENU_ACTION_REPORT_05:
                category = ReportCategory.Unlike;
                break;
        }
        return category;
    }


    /**
     * 屏幕截图
     *
     * @param repostModel
     * @return
     */
    private void saveCurrentImage(final RepostModel repostModel) {
        ThreadManager.execute(new Runnable() {
            @Override
            public void run() {
                setStatus(STATUS_SAVEING);
                View decorview = ActivityHelper.getInstance().getCurrentActivity().getWindow().getDecorView();
                decorview.setDrawingCacheEnabled(true);
                Bitmap bmp = decorview.getDrawingCache();

                if (bmp != null) {
                    try {
                        File path = new File(savePath);

                        File file = new File(filePath);

                        if (!path.exists()) {
                            path.mkdirs();
                        }
                        if (!file.exists()) {
                            file.createNewFile();
                        }

                        FileOutputStream fos = null;
                        fos = new FileOutputStream(file);
                        if (null != fos) {
                            setStatus(STATUS_SAVE_SUCCESS);
                            repostModel.filePath = file.getAbsolutePath();
                            bmp.compress(Bitmap.CompressFormat.PNG, 90, fos);
                            fos.flush();
                            fos.close();
                        } else {
                            setStatus(STATUS_SAVE_FAILER);
                        }
                    } catch (Exception e) {
                        setStatus(STATUS_SAVE_ERROR);
                    }
                } else {
                    setStatus(STATUS_SAVE_FAILER);
                }
                mHandler.obtainMessage(0, repostModel).sendToTarget();
            }
        });
    }

    private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if (msg.what == 0) {
                final RepostModel repostModel = (RepostModel) msg.obj;
                switch (getStatus()) {
                    case STATUS_SAVEING:

                        break;
                    case STATUS_SAVE_SUCCESS: // 保存成功
                        UploadFileManager.getInstance().uploadPic(repostModel.filePath, new UploadFileManager.UploadCallBack() {
                            @Override
                            public void uploadSuccess(String fileUrl) {
                                switch (repostModel.reportStatus) {
                                    case STATUS_ROOM:
                                        ProtoRequestHelper.task(ProtoHttpFactory.requestReportRoom(repostModel.roomId, repostModel.uid, repostModel.category, fileUrl)).setTag(this.hashCode()).request(protoCallBack);
                                        break;
                                    case STATUS_IMAGE:
                                        ProtoRequestHelper.task(ProtoHttpFactory.requestReportPicture(repostModel.feedId, repostModel.uid, repostModel.category, fileUrl)).setTag(this.hashCode()).request(protoCallBack);
                                        break;
                                    case STATUS_VIDEO:
                                        ProtoRequestHelper.task(ProtoHttpFactory.requestReportVideo(repostModel.feedId, repostModel.uid, repostModel.category, fileUrl)).setTag(this.hashCode()).request(protoCallBack);
                                        break;
                                    case STATUS_USER:
                                        ProtoRequestHelper.task(ProtoHttpFactory.requestReportUser(repostModel.uid, repostModel.category, fileUrl)).setTag(this.hashCode()).request(protoCallBack);
                                        break;
                                }
                            }

                            @Override
                            public void uploadFailer(int errorCode, String errorMessage) {
                                ErrorResult.toastError(mContext, R.string.tips_failer_inform);
                            }
                        });
                        break;
                    case STATUS_SAVE_FAILER: // 保存失败
                        //ErrorResult.toastError(mContext, R.string.tips_failer_inform);
                        switch (repostModel.reportStatus) {
                            case STATUS_ROOM:
                                ProtoRequestHelper.task(ProtoHttpFactory.requestReportRoom(repostModel.roomId, repostModel.uid, repostModel.category, "")).setTag(this.hashCode()).request(protoCallBack);
                                break;
                            case STATUS_IMAGE:
                                ProtoRequestHelper.task(ProtoHttpFactory.requestReportPicture(repostModel.feedId, repostModel.uid, repostModel.category, "")).setTag(this.hashCode()).request(protoCallBack);
                                break;
                            case STATUS_VIDEO:
                                ProtoRequestHelper.task(ProtoHttpFactory.requestReportVideo(repostModel.feedId, repostModel.uid, repostModel.category, "")).setTag(this.hashCode()).request(protoCallBack);
                                break;
                            case STATUS_USER:
                                ProtoRequestHelper.task(ProtoHttpFactory.requestReportUser(repostModel.uid, repostModel.category, "")).setTag(this.hashCode()).request(protoCallBack);
                                break;
                        }
                        break;
                    case STATUS_SAVE_ERROR: // 保存异常
                        //ErrorResult.toastError(mContext, R.string.tips_failer_inform);
                        switch (repostModel.reportStatus) {
                            case STATUS_ROOM:
                                ProtoRequestHelper.task(ProtoHttpFactory.requestReportRoom(repostModel.roomId, repostModel.uid, repostModel.category, "")).setTag(this.hashCode()).request(protoCallBack);
                                break;
                            case STATUS_IMAGE:
                                ProtoRequestHelper.task(ProtoHttpFactory.requestReportPicture(repostModel.feedId, repostModel.uid, repostModel.category, "")).setTag(this.hashCode()).request(protoCallBack);
                                break;
                            case STATUS_VIDEO:
                                ProtoRequestHelper.task(ProtoHttpFactory.requestReportVideo(repostModel.feedId, repostModel.uid, repostModel.category, "")).setTag(this.hashCode()).request(protoCallBack);
                                break;
                            case STATUS_USER:
                                ProtoRequestHelper.task(ProtoHttpFactory.requestReportUser(repostModel.uid, repostModel.category, "")).setTag(this.hashCode()).request(protoCallBack);
                                break;
                        }
                        break;
                }
            }
        }
    };

    /**
     * 举报回调
     */
    ProtoCallBack protoCallBack = new ProtoCallBack() {
        @Override
        public void onRequestSuccess(String command, String data) {
            Result<ProtoError> result = JSON.parseObject(data, new TypeReference<Result<ProtoError>>() {
            }.getType());
            if (result.result == ResultCode.CodeSuccess) {
                ToastUtil.show(mContext, R.string.tips_success_inform);
            } else {
                ErrorResult.toastError(mContext, result.result);
            }
        }

        @Override
        public void onRequestError(String command, int code, String message) {
            ErrorResult.toastError(mContext, code);
        }
    };


    /**
     * 获取SDCard的目录路径功能
     *
     * @return
     */
    private String getSDCardPath() {
        File sdcardDir;
        //判断SDCard是否存在
        boolean sdcardExist = Environment.getExternalStorageState().equals(android.os.Environment.MEDIA_MOUNTED);
        if (sdcardExist) {
            sdcardDir = Environment.getExternalStorageDirectory();
        } else {
            sdcardDir = ActivityHelper.getInstance().getCurrentActivity().getApplication().getFilesDir();
        }
        return sdcardDir.toString();
    }

    public int getStatus() {
        return imgStatus;
    }

    public void setStatus(int status) {
        this.imgStatus = status;
    }

    private class RepostModel {
        public int reportStatus;
        public long uid;
        public long feedId;
        public int category;
        public long roomId;
        public String filePath;
    }

    /**
     * 释放资源
     */
    public void release() {
        //通过hashCode作为tag
        ProtoRequestHelper.cancelRequest(this.hashCode());
        mHandler.removeCallbacksAndMessages(null);
    }
}
